package com.kk.springmvc.demo.common.aspect;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.kk.springmvc.demo.common.enums.ResultCodeEnum;

/**
 * 统一异常处理
 * 
 * @author chengkai
 * @since 2017/4/1
 *
 */
@ControllerAdvice(annotations = Controller.class)
public class RestControllerAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestControllerAspect.class);
    
    private final static String RETURN_CODE = "returnCode";

    private final static String RETURN_MESSAGE = "returnMsg";

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Map<String, String> errorResponse(Exception ex) {
        Map<String, String> errorResult = new HashMap<>();
        errorResult.put(RETURN_CODE, ResultCodeEnum.ERROR.getCode());
        errorResult.put(RETURN_MESSAGE, ResultCodeEnum.ERROR.getMessage());
        LOGGER.error(ExceptionUtils.getRootCauseMessage(ex));
        return errorResult;
    }

}
